<?php
namespace app\common\logic;

use Qcloud\Cos\Client;
use OSS\OssClient;
use think\facade\Db;
/**
 * Class OssLogic
 * 对象存储逻辑类
 */
class OssLogic
{
    public function oss_upload($pic){
        $oss_type = tpCache('basic.oss_type');
        if($oss_type=='tengxun'){
           return $this->tengxun($pic);
        }elseif($oss_type=='ali'){
            return $this->alioss($pic);
        }else{
            return $pic;
        }
    }
    //腾讯云上传
    public function tengxun($pic_url){
        $object = ltrim(str_replace(getCurUrl(),'public',$pic_url),'/');
        $set = Db::name('oss_set')->where(['type'=>'tengxun'])->find();
        $config = json_decode($set['config'],true);
        $secretId = $config['secretid']; //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = $config['secretkey']; //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = $config['local']; //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new Client(
            array(
                'region' => $region,
                'scheme' => 'https', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId,
                    'secretKey' => $secretKey
                ),
                'verify' => false //禁用SSL证书验证，解决自签名证书问题
            )
        );
        $local_path = ROOT_PATH.$object;

//        $printbar = function($totalSize, $uploadedSize) {
//            printf("uploaded [%d/%d]\n", $uploadedSize, $totalSize);
//        };

        try {
            $result = $cosClient->upload(
                 $config['bucket'], //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
                $object,
                 fopen($local_path, 'rb')
            );
            $picurl = $config['url'].'/'.$object;
            //上传完成删除原图
            unlink($local_path);
            return $picurl;
            // 请求成功
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }
    //阿里云上传
    public function alioss($pic_url){
        $object = ltrim(str_replace(getCurUrl(),'public',$pic_url),'/');
        $set = Db::name('oss_set')->where(['type'=>'ali'])->find();
        $config = json_decode($set['config'],true);
        $accessKeyId = $config['access_key_id'];
        $accessKeySecret = $config['secret'];
        $endpoint = $config['endpoint'];
        $bucketName = $config['bucket_name'];
        $file_path = ROOT_PATH.$object;
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
        // 先把本地的example.jpg上传到指定$bucket, 命名为$object
        $ossClient->uploadFile($bucketName, $object, $file_path);
        $picurl = $config['bucket_url'].'/'.$object;
        //上传完成删除原图
        unlink($file_path);
        //dump($picurl);exit;
        return $picurl;
    }

    //删除图片
    public static function deletepic($picurl){
        $oss_type = tpCache('basic.oss_type');
        $domain = getCurUrl();
        if(strpos($picurl,$domain) !== 0){ //非本地
            if($oss_type=='ali'){ //阿里云
                $set = Db::name('oss_set')->where(['type'=>'ali'])->find();
                $config = json_decode($set['config'],true);
                if(strpos($picurl,$config['bucket_url']) !== 0) return ['status'=>0,'msg'=>''];
                $accessKeyId = $config['access_key_id'];
                $accessKeySecret = $config['secret'];
                $endpoint = $config['endpoint'];
                $bucket= $config['bucket_name'];
                // 文件名称
                $object = ltrim(str_replace($config['bucket_url'],'',$picurl),'/');
                try{
                    $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    $ossClient->deleteObject($bucket, $object);
                    return ['status'=>1,'msg'=>''];
                } catch(OssException $e) {
                    return ['status'=>0,'msg'=>''];
                }
            }elseif($oss_type=='tengxun'){ //腾讯云
                $set = Db::name('oss_set')->where(['type'=>'tengxun'])->find();
                $config = json_decode($set['config'],true);
                if(strpos($picurl,$config['bucket']) !== 0) return ['status'=>0,'msg'=>''];
                $secretId =$config['secretid'];
                $secretKey =$config['secretkey'];
                $region = $config['local'];
                $bucket = str_replace("-".$config['appid'],'',$config['bucket'])."-".$config['appid'];
                $object = ltrim(str_replace($config['url'],'',$picurl),'/');
                try {
                    $cosClient = new \Qcloud\Cos\Client(array(
                        'region' => $region,
                        //'schema' => 'https', //协议头部，默认为http
                        'credentials'=> array('secretId'  => $secretId ,'secretKey' => $secretKey)
                    ));
                    $result = $cosClient->deleteObject(['Bucket'=>$bucket,'Key'=>$object]);
                    return ['status'=>1,'msg'=>''];
                } catch (\Exception $e){
                    echojson(['status'=>0,'msg'=>$e->getMessage()]);
                    return $picurl;
                }
            }
        }else{
            $filePath = ROOT_PATH.ltrim(str_replace($domain,'',$picurl),'/');
            @unlink($filePath);
            return ['status'=>1,'msg'=>''];
        }
    }
}